package com.car.loan.project.xr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.car.loan.common.enums.DeletedEnum;
import com.car.loan.common.exception.loan.LoanParameterException;
import com.car.loan.common.utils.SecurityUtils;
import com.car.loan.common.utils.StringUtils;
import com.car.loan.common.utils.qiniu.QiniuUtil;
import com.car.loan.framework.aspectj.lang.annotation.DataStatus;
import com.car.loan.framework.aspectj.lang.annotation.Log;
import com.car.loan.framework.aspectj.lang.enums.BusinessType;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.ve.domain.VeVehicleEvaluation;
import com.car.loan.project.ve.service.IVeVehicleEvaluationService;
import com.car.loan.project.ve.util.enums.VehicleStatus;
import com.car.loan.project.xr.domain.Loan;
import com.car.loan.project.xr.domain.LoanAlbum;
import com.car.loan.project.xr.domain.LoanStatus;
import com.car.loan.project.xr.service.ILoanAlbumService;
import com.car.loan.project.xr.service.ILoanService;
import com.car.loan.project.xr.service.ILoanStatusService;
import com.car.loan.project.xr.service.impl.LoanMakeLoansService;
import com.car.loan.project.xr.util.bo.business.LoanAlbumBo;
import com.car.loan.project.xr.util.bo.business.LoanAlbumDeleteBo;
import com.car.loan.project.xr.util.bo.business.LoanBaseInfo;
import com.car.loan.project.xr.util.bo.business.LoanBo;
import com.car.loan.project.xr.util.bo.business.LoanUpdateBo;
import com.car.loan.project.xr.util.enums.LoanBusinessAuditStatus;
import com.car.loan.project.xr.util.enums.LoanBusinessStatus;
import com.car.loan.project.xr.util.enums.LoanStatusEnum;
import com.car.loan.project.xr.util.select.LoanApplySelect;
import com.car.loan.project.xr.util.vo.BusinessDetailVo;
import com.car.loan.project.xr.util.vo.LoanApplyVo;
import com.car.loan.project.xr.util.vo.LoanMakeLoansDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 贷款Controller
 *
 * @author ruoyi
 * @date 2019-11-03
 */
@RestController
@RequestMapping("xr/loan")
@Api(value = "业务申请", tags = "车贷业务-业务申请")
public class LoanController {


    @Autowired
    private ILoanService loanService;
    @Autowired
    private ILoanStatusService loanStatusService;

    @Autowired
    private IVeVehicleEvaluationService veVehicleEvaluationService;

    @Autowired
    private ILoanAlbumService loanAlbumService;

    @PreAuthorize("@ss.hasPermi('loan:business:add')")
    @PostMapping("apply")
    @Log(title = "添加业务申请", businessType = BusinessType.INSERT)
    @ApiOperation("添加业务申请")
    public synchronized AjaxResult saveApply(@Valid @RequestBody LoanBo loanBo) {
        return loanService.apply(loanBo);
    }


    @PreAuthorize("@ss.hasPermi('loan:business:query')")
    @GetMapping("apply/list")
    @ApiOperation(value = "获取业务申请列表", notes = "状态值为0=待提交1=待审批2=已拒绝", response = LoanBaseInfo.class, responseContainer = "list")
    @DataStatus(loanStatusEnum = com.car.loan.common.enums.LoanStatusEnum.BUSINESS_STATUS)
    public AjaxResult applyList(@Valid LoanApplySelect loanApplySelect) {
        return AjaxResult.success(loanService.page(loanApplySelect));
    }


    @PreAuthorize("@ss.hasPermi('loan:business:query')")
    @GetMapping("apply/{loanId}")
    @ApiOperation(value = "获取业务申请详情", notes = "获取业务申请详情", response = LoanApplyVo.class)
    public AjaxResult getApplyInfo(@PathVariable Long loanId) {
        return AjaxResult.success(loanService.getLoanApplyVo(loanId));
    }

    @PreAuthorize("@ss.hasPermi('loan:business:edit')")
    @PutMapping("apply")
    @Log(title = "编辑业务申请", businessType = BusinessType.UPDATE)
    @ApiOperation("编辑业务申请")
    public synchronized AjaxResult updateApply(@Valid @RequestBody LoanUpdateBo loanBo) {
        return loanService.updateApply(loanBo);
    }


    @PreAuthorize("@ss.hasPermi('loan:business:withdraw')")
    @PutMapping("apply/withdraw/{loanId}")
    @Log(title = "撤回业务申请", businessType = BusinessType.WITHDRAW)
    @ApiOperation(value = "撤回业务申请", notes = "申请已审核不可撤回")
    public AjaxResult withdrawApply(@PathVariable Long loanId) {
        Optional<LoanStatus> optionalLoanStatus = loanStatusService.getByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("业务状态数据异常请联系管理员"));
        Long businessAuditStatus = loanStatus.getBusinessAuditStatus();
        if (LoanBusinessAuditStatus.INIT.status != businessAuditStatus) {
            return AjaxResult.error("当前状态不可撤回");
        }
        loanStatus.setBusinessStatus((long) LoanBusinessStatus.INIT.status);
        loanStatus.setBusinessAuditStatus((long) LoanBusinessAuditStatus.INIT.status);
        loanStatusService.updateLoanStatus(loanStatus);
        //业务状态变更
        Loan loan = new Loan();
        loan.setId(loanId);
        loan.setBusinessStatus(LoanStatusEnum.INIT.status);
        loanService.updateLoan(loan);
        return AjaxResult.success();
    }


    @PreAuthorize("@ss.hasPermi('loan:business:album')")
    @PostMapping("album")
    @ApiOperation(value = "添加附件", notes = "在业务提交后才可使用，只用于图片，视频上传")
    @Log(title = "添加附件", businessType = BusinessType.INSERT)
    public synchronized AjaxResult saveImages(@Valid @RequestBody LoanAlbumBo loanAlbumBo) {
        LoanAlbum loanAlbum = new LoanAlbum();
        loanAlbum.setLoanId(loanAlbumBo.getLoanId());
        loanAlbum.setType(loanAlbumBo.getType());
        loanAlbum.setUrl(loanAlbumBo.getUrl());
        loanAlbumService.insertLoanAlbum(loanAlbum);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('loan:business:album:delete')")
    @DeleteMapping("album")
    @ApiOperation(value = "删除附件", notes = "在业务提交后才不可使用")
    @Log(title = "删除附件", businessType = BusinessType.DELETE)
    public AjaxResult deleteImages(@Valid @RequestBody LoanAlbumDeleteBo loanAlbumDeleteBo) {
        Optional<LoanStatus> optionalLoanStatus = loanStatusService
            .getByLoanId(loanAlbumDeleteBo.getLoanId());
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("该业务状态数据异常，请联系管理员"));
        if (LoanBusinessStatus.INIT.status != loanStatus.getBusinessStatus()) {
            return AjaxResult.error("当前业务状态不可删除");
        }
        loanAlbumService.deleteLoanAlbumById(loanAlbumDeleteBo.getId());
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('loan:business:delete')")
    @DeleteMapping("delete/{loanId}")
    @Log(title = "业务申请删除", businessType = BusinessType.DELETE)
    @ApiOperation("业务申请删除")
    public AjaxResult creditDelete(@PathVariable Long loanId) {
        Optional<LoanStatus> optionalLoanStatus = loanStatusService
            .getByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("该业务状态数据异常，请联系管理员"));
        if (LoanBusinessStatus.INIT.status != loanStatus.getBusinessStatus()) {
            return AjaxResult.error("当前业务状态不可删除");
        }
        Loan loan = loanService.selectLoanById(loanId);
        loan.setDeleted(DeletedEnum.DELETED.getCode());
        loan.setDeletedId(SecurityUtils.getLoginUserId());
        loan.setDeletedTime(LocalDateTime.now());
        loanService.updateLoan(loan);
        return AjaxResult.success();
    }


    @GetMapping("getContractAmount/{frameNo}")
    @ApiOperation(value = "按照车架号获取合同车价", response = VeVehicleEvaluation.class)
    public AjaxResult getContractAmount(
        @ApiParam(value = "车架号", required = true) @PathVariable String frameNo) {
        VeVehicleEvaluation veVehicleEvaluationQuery = new VeVehicleEvaluation();
        veVehicleEvaluationQuery.setFrameNo(frameNo);
        veVehicleEvaluationQuery.setStatus(VehicleStatus.COMPLETE.status);
        QueryWrapper<VeVehicleEvaluation> queryWrapper = new QueryWrapper<>(
            veVehicleEvaluationQuery);
        queryWrapper.orderByDesc("evaluation_date");
        queryWrapper.last("limit 1");
        queryWrapper.select("id,evaluation_price");
        List<VeVehicleEvaluation> veVehicleEvaluations = veVehicleEvaluationService
            .selectVeVehicleEvaluationQueryList(queryWrapper);
        if (StringUtils.isNotEmpty(veVehicleEvaluations)) {
            return AjaxResult.success(veVehicleEvaluations.get(0));
        }
        return AjaxResult.success(new VeVehicleEvaluation());
    }


    @PreAuthorize("@ss.hasPermi('loan:business:query')")
    @GetMapping("apply/business/list")
    @ApiOperation(value = "获取业务列表", response = LoanBaseInfo.class, responseContainer = "list")
    @DataStatus(loanStatusEnum = com.car.loan.common.enums.LoanStatusEnum.BUSINESS_LIST)
    public AjaxResult businessList(@Valid LoanApplySelect loanApplySelect) {
        return AjaxResult.success(loanService.page(loanApplySelect));
    }


    @PreAuthorize("@ss.hasPermi('loan:business:query')")
    @GetMapping("apply/business/{loanId}")
    @ApiOperation(value = "获取业务列表详情", response = BusinessDetailVo.class)
    public AjaxResult businessInfo(@PathVariable Long loanId) {
        return AjaxResult.success(loanService.businessDetail(loanId));
    }

}
